package com.health.userbackstage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.userbackstage.mapper.PermissionMapper;
import com.health.userbackstage.mapper.UserMapper;
import com.health.userbackstage.pojo.Permission;
import com.health.userbackstage.pojo.User;
import com.health.userbackstage.pojo.result.Result;
import com.health.userbackstage.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService, UserDetailsService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.err.println(username);
        LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, username);
        User user = userMapper.findUserByUsername(username);
        System.err.println(user.getPassword());
        if (user != null){
            List<String> roleName = userMapper.findRoleNamesByUsername(username);
            String[] roles = null;
            if (roleName == null || roleName.size() == 0){
                roles = new String[]{"DEFAULT"};
            }else {
                roles = roleName.toArray(new String[0]);
            }
            return org.springframework.security.core.userdetails.User
                    .withUsername(username)
                    .password(user.getPassword())
                    .authorities(roles)
                    .build();
        }
        return null;
    }
}
